package com.sunshuo.springsecuritydemo.controller;

import com.sunshuo.springsecuritydemo.pojo.User;
import com.sunshuo.springsecuritydemo.service.UserService;
import com.sunshuo.springsecuritydemo.util.AuthUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @ClassName UserController
 * @Description
 * @Author sunshuo
 * @Date 2021/11/7 19:11
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/page")
    @ResponseBody
    public String page() {
        JSONObject result = new JSONObject();
        result.put("url", "/user/user.jsp");
        return result.toString();
    }

    @RequestMapping("/query")
    @ResponseBody
    public String userList() {
        List<User> users = userService.getUsers();
        JSONObject result = new JSONObject();
        result.put("code", 0);
        result.put("msg", "");
        result.put("count", users.size());
        JSONArray data = new JSONArray();
        users.forEach(user -> {
            JSONObject userJSON = new JSONObject();
            userJSON.put("id", user.getId());
            userJSON.put("username", user.getUsername());
            userJSON.put("fullname", user.getFullname());
            data.put(userJSON);
        });
        result.put("data", data);
        return result.toString();
    }

    @RequestMapping("/user_info")
    @ResponseBody
    public User getUserInfo() {
        return AuthUtils.getPrincipal();
    }

}
